#!/bin/bash
#
#  Copyright (c) 2017, The OpenThread Authors.
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. Neither the name of the copyright holder nor the
#     names of its contributors may be used to endorse or promote products
#     derived from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
#

set -euxo pipefail

cd "$(dirname "$0")/.."

die()
{
    echo >&2 " *** ERROR:  $*"
    exit 1
}

have()
{
    # This function checks if a tool is available
    #

    command -v "$1" >/dev/null 2>/dev/null
}

have_or_die()
{
    # This function verifies a tool is available and dies with proper
    # information if not available.
    #

    have "$1" || die "$1 not available!"
}

with()
{
    # This function verifies a flag is on.
    #
    # NOTE environment settings takes higher priority than default files.
    #

    local value
    value=$(printenv "$1")
    if [[ -z $value ]]; then
        if [[ -f examples/platforms/$PLATFORM/default ]]; then
            # shellcheck source=examples/platforms/raspbian/default
            value="$(. "examples/platforms/$PLATFORM/default" && eval echo "\${$1-}")"
        fi
    fi

    [[ $value == 1 ]]
}

without()
{
    # This function verifies a flag is off.
    #
    # NOTE environment settings takes higher priority than default files.
    #

    ! with "$1"
}

HAVE_SYSTEMCTL=0
if have systemctl; then
    HAVE_SYSTEMCTL=1
fi
HAVE_SERVICE=0
if have service; then
    HAVE_SERVICE=1
fi

start_service()
{
    local service_name=$1
    if [[ ${HAVE_SYSTEMCTL} == 1 ]]; then
        systemctl is-active "$service_name" || sudo systemctl start "$service_name" || die "Failed to start $service_name!"
    elif [[ ${HAVE_SERVICE} == 1 ]]; then
        sudo service "$service_name" status || sudo service "$service_name" start || echo "Failed to start $service_name!"
    else
        die 'Unable to find service manager. Try script/console to start in console mode!'
    fi
}

stop_service()
{
    local service_name=$1
    if [[ ${HAVE_SYSTEMCTL} == 1 ]]; then
        systemctl is-active "$service_name" && sudo systemctl stop "$service_name" || echo "Failed to stop $service_name!"
    elif [[ ${HAVE_SERVICE} == 1 ]]; then
        sudo service "$service_name" status && sudo service "$service_name" stop || echo "Failed to stop $service_name!"
    else
        die 'Unable to find service manager. Try script/console to stop in console mode!'
    fi
}

# Platform information is needed to load hooks and default settings.

if [[ ! ${PLATFORM+x} ]]; then
    case "${OSTYPE}" in
        darwin*)
            PLATFORM=macOS
            ;;
        *)
            have_or_die lsb_release
            PLATFORM=$(lsb_release -i | cut -c17- | tr '[:upper:]' '[:lower:]')
            ;;
    esac
fi
echo "Current platform is $PLATFORM"

# The DHCPV6_PD feature requires IPv6 features in dhcpcd but RIO
# is not supported within dhcpcd.
with BORDER_ROUTING && with DHCPV6_PD && die "BORDER_ROUTING and DHCPV6_PD cannot coexist!"

STAGE_DIR=$PWD/stage
BUILD_DIR=$PWD/build

[[ -d $STAGE_DIR ]] || mkdir -v -p "$STAGE_DIR"
[[ -d $BUILD_DIR ]] || mkdir -v -p "$BUILD_DIR"

export PATH=$STAGE_DIR/usr/bin:$STAGE_DIR/usr/sbin:$PATH

TASKNAME=$(basename "$0")
BEFORE_HOOK=examples/platforms/$PLATFORM/before_$TASKNAME
AFTER_HOOK=examples/platforms/$PLATFORM/after_$TASKNAME
if [[ ! -f $BEFORE_HOOK ]]; then
    BEFORE_HOOK=/dev/null
fi
if [[ ! -f $AFTER_HOOK ]]; then
    AFTER_HOOK=/dev/null
fi
